package net.cl.utils;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

/**
 * 
 * @author caol64@gmail.com
 */
public class IOUtil {

	private static final int DEFAULT_BUFFER_SIZE = 2048;
	public static final String UNIVERSAL_CHARDET = "org.mozilla.universalchardet.UniversalDetector";

	public static void closeQuietly(InputStream input) {
		try {
			if (input != null)
				input.close();
		} catch (IOException ioe) {
		}
	}

	public static void closeQuietly(OutputStream output) {
		try {
			if (output != null)
				output.close();
		} catch (IOException ioe) {
		}
	}

	public static void closeQuietly(Reader input) {
		try {
			if (input != null)
				input.close();
		} catch (IOException ioe) {
		}
	}

	public static void closeQuietly(Writer output) {
		try {
			if (output != null)
				output.close();
		} catch (IOException ioe) {
		}
	}

	public static String toString(InputStream input) throws IOException {
		return toString(input, null);
	}

	public static String toString(InputStream input, String encoding) throws IOException {
		if (input == null)
			throw new NullPointerException("inputStream");
		BufferedInputStream bis = new BufferedInputStream(input);
		int n = 0;
		InputStreamReader in;
		char[] buffer = new char[DEFAULT_BUFFER_SIZE];
		StringWriter sw = new StringWriter();
		if (encoding == null)
			in = new InputStreamReader(bis);
		else
			in = new InputStreamReader(bis, encoding);
		while (-1 != (n = in.read(buffer))) {
			sw.write(buffer, 0, n);
		}
		closeQuietly(bis);
		return sw.toString();
	}

	/**
	 * return stream size
	 */
	public static long copy(InputStream input, OutputStream output) throws IOException {
		if (input == null)
			throw new NullPointerException("inputStream");
		if (output == null)
			throw new NullPointerException("outputStream");
		byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
		long count = 0;
		int n = 0;
		while (-1 != (n = input.read(buffer))) {
			output.write(buffer, 0, n);
			count += n;
		}
		output.flush();
		return count;
	}

	public static long copyAndClose(InputStream input, OutputStream output) throws IOException {
		long count = copy(input, output);
		closeQuietly(input);
		closeQuietly(output);
		return count;
	}

	public static byte[] toByteArray(InputStream input) throws IOException {
		if (input == null)
			throw new NullPointerException("inputStream");
		BufferedInputStream bis = new BufferedInputStream(input);
		byte[] byteArray = new byte[bis.available()];
		bis.read(byteArray);
		closeQuietly(bis);
		return byteArray;
	}

}
